package org.example.clouddemo.service.common.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.example.clouddemo.bean.common.entity.Stock;



import org.example.clouddemo.service.common.mapper.StockMapper;

import org.example.common.api.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements StockService {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean checkStock(Long productId, Integer quantity) {
        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("product_id", productId));
        return stock != null && stock.getQuantity() >= quantity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean reduceStock(Long productId, Integer quantity) {
        // 乐观锁更新库存，防止超卖
        Stock stock = stockMapper.selectOne(new QueryWrapper<Stock>().eq("product_id", productId));
        if (stock == null || stock.getQuantity() < quantity) {
            return false;
        }
        
        // 使用乐观锁更新，version字段用于控制并发
        stock.setQuantity(stock.getQuantity() - quantity);
        int result = stockMapper.updateById(stock);
        return result > 0;
    }


}